package leetcode.problems;

import org.junit.Test;

/**
 * Created by gmwang on 2018/7/25
 * Middle of the Linked List
 * 链表中间值
 */
public class _0808MiddleOfTheLinkedList {
    /**
     *
     Given a non-empty, singly linked list with head node head, return a middle node of linked list.
     给定一个非空的、带有头节点头的单链表，返回链表的中间节点。

     If there are two middle nodes, return the second middle node.
     如果有两个中间节点，则返回第二中间节点。

     Example 1:

     Input: [1,2,3,4,5]
     Output: Node 3 from this list (Serialization: [3,4,5])
     The returned node has value 3.  (The judge's serialization of this node is [3,4,5]).
     Note that we returned a ListNode object ans, such that:
     ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
     Example 2:

     Input: [1,2,3,4,5,6]
     Output: Node 4 from this list (Serialization: [4,5,6])
     Since the list has two middle nodes with values 3 and 4, we return the second one.


     Note:

     The number of nodes in the given list will be between 1 and 100.
    /**
     *
     * @param head
     * @return
     */
    public ListNode middleNode(ListNode head) {
        ListNode listNode;
        ListNode listNodeHead = head;
        int size = 0;
        //获取长度
        while( head.next != null){
            head = head.next;
            size++;
        }
        //判断奇数偶数
        if(size/2.0%1==0 ){
            size = size/2;
        }else {
            size = size/2+1;
        }
        int res = 0;
        while(listNodeHead.next != null){
            if(res >= size){
                listNode = listNodeHead;
                return listNode;
            }
            listNodeHead = listNodeHead.next;
            res++;
        }
        return head;
    }
    @Test
    public void test() {
        ListNode listNode1 = new ListNode(1);
//        ListNode listNode2 = new ListNode(2);
//        ListNode listNode3 = new ListNode(3);
//        ListNode listNode4 = new ListNode(4);
//        ListNode listNode5 = new ListNode(5);
//        ListNode listNode6 = new ListNode(6);
//        listNode1.next = listNode2;
//        listNode2.next = listNode3;
//        listNode3.next = listNode4;
//        listNode4.next = listNode5;
//        listNode5.next = listNode6;
//        ListNode s = middleNode(listNode1);
        ListNode s = middleNode(listNode1);
        System.out.println(s.val+","+s.next.val+","+s.next.next.val);
    }
    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
}



